package gen.tools.role;

import gen.tools.Widgets;
import gen.tools.structures.RoleAssign;
import gen.tools.structures.S2;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class UpdateEmpRole extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public UpdateEmpRole() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/json");
		response.setCharacterEncoding( wid.UIcodeSet );
		
		final String subsysId = request.getParameter("subsysId");
		final int roleId = Integer.parseInt( request.getParameter("roleId") );
		final String empId = request.getParameter("empId");					
		final String creatorId = request.getParameter("creatorId");			//進行這次異動的當事人
		final String addOrDelete = request.getParameter("addOrDelete");
		
		String sql = "";
		String res = "";
		
		Connection conn = null;
		PreparedStatement ps = null;
		
		try {
			conn = wid.getConn();
			
			if ( "add".equalsIgnoreCase( addOrDelete ) ) {
				sql = "INSERT INTO mpemprolesubsys (subsysId,roleId,empId,creatorId,cDT) VALUES (?,?,?,?,?)";
			} else {
				sql = "DELETE FROM mpemprolesubsys WHERE subsysId=? AND roleId=? AND empId=?";
			}
			ps = conn.prepareStatement(sql);
			ps.setString(1, subsysId);
			ps.setInt(2, roleId);
			ps.setString(3, empId);
			if ( "add".equalsIgnoreCase( addOrDelete ) ) {
				ps.setString(4, creatorId);
				ps.setTimestamp(5, wid.cDT());
			}
			ps.execute();
		} catch (Exception e) {
			wid.errLog(e);
			res = wid.errProcess(e);
		} finally {
			try {
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}	
			} catch (Exception e) { e.printStackTrace(); };
			
		}
		response.getWriter().write(res);
	}

}
